package com.shengdong.water.code.utils
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import androidx.core.app.ActivityCompat
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt

object LocationUtil  {

    private var locationManager: LocationManager? = null
    private var locationTimeoutJob: Job? = null
    private var locationListener: LocationListener? = null

    private const val TIMEOUT = 20000L // 超时时间 20秒
    private const val ACCURACY_THRESHOLD = 50.0f // 精度阈值(米)
    private const val MIN_TIME = 1000L // 最小更新时间(毫秒)
    private const val MIN_DISTANCE = 10.0f // 最小更新距离(米)


    private var isInitialized = false

    fun init(context: Context) {
        if (!isInitialized) {
            locationManager = context.applicationContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
            isInitialized = true
        }
    }


    fun checkLocationPermission(context: Context): Boolean {
        return ActivityCompat.checkSelfPermission(
            context.applicationContext,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(
                    context,
                    Manifest.permission.ACCESS_COARSE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
    }

    @SuppressLint("MissingPermission")
    fun requestLocation(
        context: Context,
//        outletLat: Double,  // 排污口纬度
//        outletLon: Double,
        onLocationResult: (latitude: Double, longitude: Double) -> Unit,
        onError: (String) -> Unit,
        onLoading: (String) -> Unit,
        onLoadingDismiss: () -> Unit
    ) {
        if (!isInitialized) {
            init(context)
        }
        if (!checkLocationPermission(context)) {
            onError("需要位置权限")
            return
        }

        onLoading("获取位置中...")

        // 设置超时
        locationTimeoutJob = MainScope().launch {
            delay(TIMEOUT)
            stopLocationUpdates()
            onLoadingDismiss()
            onError("获取位置超时")
        }


        locationListener = object : LocationListener {
            override fun onLocationChanged(location: Location) {
                if (location.accuracy > ACCURACY_THRESHOLD) {
                    return
                }

                locationTimeoutJob?.cancel()
//                val distance = calculateDistance(
//                    outletLat,
//                    outletLon,
//                    location.latitude,
//                    location.longitude
//                )
                onLocationResult(location.latitude, location.longitude)
                stopLocationUpdates()
                onLoadingDismiss()
            }

            override fun onProviderDisabled(provider: String) {
                locationTimeoutJob?.cancel()
                stopLocationUpdates()
                onLoadingDismiss()
                onError("位置服务已关闭")
            }

            override fun onProviderEnabled(provider: String) {}
            override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
        }

        try {
            // 优先使用GPS定位
            if (locationManager?.isProviderEnabled(LocationManager.GPS_PROVIDER) == true) {
                locationManager?.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    MIN_TIME,
                    MIN_DISTANCE,
                    locationListener!!
                )
                return
            }

            // 如果GPS不可用,使用网络定位
            if (locationManager?.isProviderEnabled(LocationManager.NETWORK_PROVIDER) == true) {
                locationManager?.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER,
                    MIN_TIME,
                    MIN_DISTANCE,
                    locationListener!!
                )
                return
            }

            // 都不可用
            locationTimeoutJob?.cancel()
            onLoadingDismiss()
            onError("请开启位置服务")
        } catch (e: Exception) {
            locationTimeoutJob?.cancel()
            onLoadingDismiss()
            onError("定位失败: ${e.message}")
        }
    }

    /**
     * 计算两点之间的距离(米)
     * @param lat1 第一个点的纬度
     * @param lon1 第一个点的经度
     * @param lat2 第二个点的纬度
     * @param lon2 第二个点的经度
     * @return 距离(米)
     */
    fun calculateDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
        val r = 6371000.0 // 地球半径(米)

        val lat1Rad = Math.toRadians(lat1)
        val lat2Rad = Math.toRadians(lat2)
        val deltaLat = Math.toRadians(lat2 - lat1)
        val deltaLon = Math.toRadians(lon2 - lon1)

        val a = sin(deltaLat / 2) * sin(deltaLat / 2) +
                cos(lat1Rad) * cos(lat2Rad) *
                sin(deltaLon / 2) * sin(deltaLon / 2)

        val c = 2 * atan2(sqrt(a),sqrt(1 - a))

        return r * c
    }

    fun stopLocationUpdates() {
        locationListener?.let { locationManager?.removeUpdates(it) }
        locationTimeoutJob?.cancel()
        locationListener = null
    }
}